package blog.service.impl;

import blog.common.Result;
import blog.entity.UserAction;
import blog.mapper.UserActionMapper;
import blog.service.UserActionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserActionServiceImpl extends ServiceImpl<UserActionMapper, UserAction> implements UserActionService {


    @Override
    public Result findUserArticleAction(int uid, int aid) {
        UserAction userAction = baseMapper.selectOne(new LambdaQueryWrapper<UserAction>().eq(UserAction::getUid, uid).eq(UserAction::getAid, aid));
        if (userAction==null){
            return Result.error("未找到该用户对该文章的操作");
        }
        //统计点赞数
        int likeCount = baseMapper.selectCount(new LambdaQueryWrapper<UserAction>().eq(UserAction::getAid, aid).isNotNull(UserAction::getScore));

        //统计评论量，评论量不为null
        int commentCount = baseMapper.selectCount(new LambdaQueryWrapper<UserAction>().eq(UserAction::getAid, aid).isNotNull(UserAction::getComment));
        //统计该文章的所有评论
        List<UserAction> userActionList = baseMapper.selectList(new LambdaQueryWrapper<UserAction>().eq(UserAction::getAid, aid).isNotNull(UserAction::getComment));
        //整合数据
        Map<String,Object> map = new HashMap<>();
        map.put("userAction",userAction);
        map.put("likeCount",likeCount);
        map.put("commentCount",commentCount);
        map.put("userActionList",userActionList);
        return Result.success(map);
    }

    @Override
    public Result addUserScore(int uid, int aid, int score) {
        UserAction userAction = baseMapper.selectOne(new LambdaQueryWrapper<UserAction>().eq(UserAction::getUid, uid).eq(UserAction::getAid, aid));
        if (userAction==null){
           //如果没有记录，就新建一条记录
            userAction = new UserAction();
            userAction.setUid(uid);
            userAction.setAid(aid);
            userAction.setScore(score);
            baseMapper.insert(userAction);
            return Result.success(userAction);
        }
        userAction.setScore(score);
        baseMapper.updateById(userAction);
        return Result.success(userAction);
    }

    @Override
    public Result findUserScore(int uid, int aid) {
        UserAction userAction = baseMapper.selectOne(new LambdaQueryWrapper<UserAction>().eq(UserAction::getUid, uid).eq(UserAction::getAid, aid));
        if (userAction==null){
            return Result.error("未找到该用户对该文章的操作");
        }
        return Result.success(userAction);
    }


}